# views.py
from django.views.generic import CreateView, ListView
from django.urls import reverse_lazy

from .form import BookForm
from .models import Book


class BookCreateView(CreateView):
    model = Book
    # 指定要在表单中显示的字段
    # fields = '__all__'
    form_class = BookForm
    template_name = 'book_form.html'
    # 成功提交后跳转的URL
    success_url = reverse_lazy('book-list')
    # 额外传递到模板的上下文数据
    extra_context = {'title': '添加新书籍'}

    def form_valid(self, form):
        """表单验证通过后的处理"""
        print(f"即将保存书籍: {form.cleaned_data['title']}")
        return super().form_valid(form)

    def form_invalid(self, form):
        """表单验证失败后的处理"""
        print("表单验证失败")
        print("错误信息:", form.errors)
        return super().form_invalid(form)


# 用于展示书籍列表的视图
class BookListView(ListView):
    model = Book
    template_name = 'book_list.html'
    context_object_name = 'books'
    extra_context = {'title': '书籍列表'}
